import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import '../style/WordListPage.css';
import { get } from '../apiService'; // 导入get函数

const WordListPage = () => {
  const [wordList, setWordList] = useState([]);
  const [search_term, setSearchTerm] = useState('');
  const [page, setCurrentPage] = useState(1);
  const [total_pages, setTotalPages] = useState(0);
  

  useEffect(() => {
    fetchWordList();
  }, [page, search_term]);

  const fetchWordList = async () => {
    try {
      // 使用get函数发送请求
      const response = await get('/vocabulary', { page: page, search_term: search_term });
      setWordList(response.items);
      setTotalPages(response.total_pages);
    } catch (error) {
      console.error('请求错误:', error);
    }
  };

  const handlePrevPage = () => {
    setCurrentPage((prevPage) => Math.max(prevPage - 1, 1));
  };

  const handleNextPage = () => {
    setCurrentPage((prevPage) => Math.min(prevPage + 1, total_pages));
  };

  const handleSearch = (e) => {
    setSearchTerm(e.target.value);
    setCurrentPage(1);
  };

  return (
    <div className="word-list">
      <h2>单词列表</h2>
      <div className="search-box">
        <input
          type="text"
          placeholder="搜索单词"
          value={search_term}
          onChange={handleSearch}
        />
      </div>
      <ul className="word-items">
      {wordList.map((word) => (
          <li key={word.id}>
             <Link to={`/word/${word.id}`}></Link>
            <div>ID: {word.id}</div>
            <div>Term: {word.term}</div>
            <div>Attr: {word.attr}</div>
            <div>Synonyms: {word.synonyms}</div>
            <div>Collocates: {word.collocates}</div>
            {/* 其他单词属性的渲染 */}
          </li>
        ))}
      </ul>
      <div className="pagination">
        <button onClick={handlePrevPage} disabled={page === 1}>上一页</button>
        <span>{page} / {total_pages}</span>
        <button onClick={handleNextPage} disabled={page === total_pages}>下一页</button>
      </div>
    </div>
  );
};

export default WordListPage;
